// pagesWorkOrder/workOrderEva/workOrderEva.js
const mixin_formItemType = require('../../common/mixins/formItemType')
import Signature from 'mini-smooth-signature';
// base64转本地
function base64ToPath(dataURL) {
  return new Promise((resolve, reject) => {
    // const data = wx.base64ToArrayBuffer(dataURL.replace(/^data:image\/\w+;base64,/, ""));
    const data = dataURL.replace(/^data:image\/\w+;base64,/, "");
    const filePath = `${wx.env.USER_DATA_PATH}/${Math.random().toString(32).slice(2)}.png`;
    wx.getFileSystemManager().writeFile({
      filePath,
      data,
      encoding: 'base64',
      success: () => resolve(filePath),
      fail: reject,
    });
  })
}
Page({
  behaviors: [mixin_formItemType],
  /**
   * 页面的初始数据
   */
  data: {
    // 评价时间
    evaTime: null,
    //  签名
    autograph: null,
    //  意见与建议
    commentSuggestion: null,
    //  附件
    enclosureList: null,
    //  工单号
    orderNum: null,
    //  响应时效
    responsePrescription: null,
    //  服务态度
    serviceAttitude: null,
    //  服务质量
    serviceQuality: null,

    show: false,
    width: 320,
    height: 600,
    scale: 2,
  },
  // 显示签名
  showSign() {
    this.setData({
      show: true
    })
  },
  // 取消签名
  cancelSign() {
    this.setData({
      show: false,
    })
    this.signature.clear()
  },
  // 重签
  resetSign() {
    this.signature.clear()

  },
  // 确定
  confirmSign() {
    console.log('confirmSignconfirmSignconfirmSign');
    if (this.signature.isEmpty()) {
      wx.showToast({
        icon: 'none',
        title: '未签名'
      });
      return;
    }
    this.getRotateImage().then(url => {
      url && wx.previewImage({
        current: 0,
        urls: [url],
      });
    });
  },
  // 全屏输出旋转图片
  async getRotateImage() {
    const self = this
    const dataURL = this.signature.toDataURL();
    const url = await base64ToPath(dataURL);
    const ctx = wx.createCanvasContext('signature');
    const width = this.signature.width;
    const height = this.signature.height;
    ctx.restore();
    ctx.save();
    ctx.translate(0, height);
    ctx.rotate(270 * Math.PI / 180);
    ctx.drawImage(url, 0, 0, width, height);
    ctx.draw();
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        wx.canvasToTempFilePath({
          canvasId: 'signature',
          canvas: self.canvas,
          x: 0,
          y: height - width,
          width: height,
          height: width,
          success: res => resolve(res.tempFilePath),
          fail: reject,
        })
      }, 50)
    })
  },


  onAfterEnter() {
    try {
      const {
        windowWidth,
        windowHeight,
        pixelRatio
      } = wx.getSystemInfoSync();
      this.setData({
        width: windowWidth - 80,
        height: windowHeight - 20,
        scale: Math.max(pixelRatio || 1, 2),
      })
    } catch (e) {}
    this.initSignature()
  },
  // 初始化
  initSignature() {
    console.log('initSignatureinitSignatureinitSignature');
    wx.createSelectorQuery().select('#signature').fields({
      node: true,
      size: true
    }).exec((res) => {
      console.log(res, 'node');
      const canvas = res[0].node;
      this.canvas = canvas;
      canvas.width = this.data.width * this.data.scale;
      canvas.height = this.data.height * this.data.scale;
      const ctx = canvas.getContext('2d');
      this.signature = new Signature(ctx, {
        width: this.data.width,
        height: this.data.height,
        scale: this.data.scale,
        minWidth: 4,
        maxWidth: 10,
        bgColor: '#fff',
        toDataURL: (type, quality) => canvas.toDataURL(type, quality),
        requestAnimationFrame: (fn) => canvas.requestAnimationFrame(fn),
        getImagePath: () => new Promise((resolve, reject) => {
          const img = canvas.createImage();
          img.onerror = reject;
          img.onload = () => resolve(img);
          img.src = canvas.toDataURL();
        })
      })
    })
  },
  handleTouchStart(e) {
    const pos = e.touches[0];
    this.signature.onDrawStart(pos.x, pos.y);
  },
  handleTouchMove(e) {
    const pos = e.touches[0];
    this.signature.onDrawMove(pos.x, pos.y);
  },
  handleTouchEnd() {
    this.signature.onDrawEnd();
  },


  setEvaTime() {

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})